#include "CServer.h"
#include "HttpConnection.h"
#include "AsioIOServicePool.h"

CServer::CServer(boost::asio::io_context& ioc, unsigned short& port)
	: m_ioc(ioc)
	, m_acceptor(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
	
}

CServer::~CServer()
{
	std::cout << "GateServer destruct......" << std::endl;
}

// 开启服务器，监听对端连接
void CServer::start()
{
	auto self = shared_from_this();
	auto& io_context = AsioIOServicePool::getInstance()->getIOService();
	std::shared_ptr<HttpConnection> new_con = std::make_shared<HttpConnection>(io_context);
	m_acceptor.async_accept(new_con->getSocket(), [self, new_con](boost::beast::error_code ec) {
		try {
			if (ec) {
				self->start();
				return;
			}

			// 处理新连接，创建HttpConnection类管理http连接
			new_con->start();
			// 继续进行监听
			self->start();
		}	
		catch (const std::exception& exp) {
			std::cout << "exception is " << exp.what() << std::endl;
			self->start();
		}
	});
}
